package com.sn.utils;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.beans.BeanInfo;

public class BeanListHander<T> implements IResultSetHander<List<T>> {

	//javabean的类型
	private Class<T> classType;
	public BeanListHander(Class<T> classType){
		this.classType = classType;
	}
	
	@Override
	public List<T> handle(ResultSet rs) throws Exception {
		List<T> list = new ArrayList<>();
		while (rs.next()) {
			T obj = classType.newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(classType, Object.class);
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds) {
				String name = pd.getName(); //列名(属性名称)
				Object value = rs.getObject(name);//列值
				//调用属性的setter方法，给对象设置数据
				pd.getWriteMethod().invoke(obj, value);
			}
			list.add(obj);
		}
		return list;
	}
	
}
